package com.youyun56.gps.android;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;

import com.youyun56.gps.android.broadcast.CloseSystemDialogBroadCast;
import com.youyun56.gps.android.commands.CommandType;
import com.youyun56.gps.android.common.CommandFactory;
import com.youyun56.gps.android.http.HttpManager;
import com.youyun56.gps.android.http.IHttpListener;
import com.youyun56.gps.android.pojo.Car;
import com.youyun56.gps.android.service.LocationUploadService;

public class MainTabActivity extends TabActivity implements OnCheckedChangeListener {
    private RadioGroup mainTab;
    private TabHost mTabHost;

    // 内容Intent
    private Intent goodInfoIntent;
    private Intent mNewsIntent;
    private Intent userinfoIntent;
    private Intent mSearchIntent;
    private Intent mMoreIntent;
    private final static String TAB_TAG_GoodInfo = "tab_tag_goodinfo";
    private final static String TAB_TAG_IM = "tab_tag_ims";
    private final static String TAB_TAG_INFO = "tab_tag_info";
    private final static String TAB_TAG_POSITION = "tab_tag_position";
    private final static String TAB_TAG_MORE = "tab_tag_more";
    private final static String tag = MainTabActivity.class.getName();
    public static LocationUploadService service;

    public static ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO
            // Auto-generated
            // method
            // stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            // TODO
            // Auto-generated
            // method
            // stub
            service = ((LocationUploadService.MyBinder) binder).getService();
            service.regBroadCase();
            service.setRunStep(RunStep.MAIN);
            if (service == null) {
                Log.i(tag, "service is not catched");
            } else {
                Log.i(tag, "service catched successful");
            }
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindService();
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.maintab);
        mainTab = (RadioGroup) findViewById(R.id.main_tab);
        mainTab.setOnCheckedChangeListener(this);
        prepareIntent();
        setupIntent();

    }

    @Override
    protected void onDestroy() {
        CloseSystemDialogBroadCast.setOpen(false);
        service.setRunStep(RunStep.NONE);
        service.write(CommandFactory.LOGOUT());
        service.unRegBroadCase();
        if (service.getCar().getPartner() == LocationUploadService.gpsUpload) {
            unbindService(mServiceConnection);
            super.onDestroy();
        } else {
            Intent intent = new Intent();
            intent.setClass(this, LocationUploadService.class);
            getApplicationContext().stopService(intent);
            super.onDestroy();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    /**
     * 准备tab的内容Intent
     */
    private void prepareIntent() {
        goodInfoIntent = new Intent(this, GoodInfoActivity.class);
        mNewsIntent = new Intent(this, ImsActivity.class);
        userinfoIntent = new Intent(this, UserInfoActivity.class);
        mSearchIntent = new Intent(this, CarStatusActivity.class);
        mMoreIntent = new Intent(this, MoreActivity.class);
    }

    /**
	 * 
	 */
    private void setupIntent() {
        this.mTabHost = getTabHost();
        TabHost localTabHost = this.mTabHost;
        localTabHost.addTab(buildTabSpec(TAB_TAG_GoodInfo, R.string.goodInfo, R.drawable.icon_1_n, goodInfoIntent));
        localTabHost.addTab(buildTabSpec(TAB_TAG_IM, R.string.main_news, R.drawable.icon_2_n, mNewsIntent));
        localTabHost.addTab(buildTabSpec(TAB_TAG_INFO, R.string.main_my_info, R.drawable.icon_3_n, userinfoIntent));
        localTabHost.addTab(buildTabSpec(TAB_TAG_POSITION, R.string.menu_position, R.drawable.icon_4_n, mSearchIntent));
        localTabHost.addTab(buildTabSpec(TAB_TAG_MORE, R.string.more, android.R.drawable.ic_menu_help, mMoreIntent));
    }

    /**
     * 构建TabHost的Tab页
     * 
     * @param tag
     *            标记
     * @param resLabel
     *            标签
     * @param resIcon
     *            图标
     * @param content
     *            该tab展示的内容
     * @return 一个tab
     */
    private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon, final Intent content) {
        return this.mTabHost.newTabSpec(tag).setIndicator(getString(resLabel), getResources().getDrawable(resIcon))
                .setContent(content);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
        case R.id.radioGoodInfo:
            this.mTabHost.setCurrentTabByTag(TAB_TAG_GoodInfo);
            break;
        case R.id.radioIms:
            this.mTabHost.setCurrentTabByTag(TAB_TAG_IM);
            break;
        case R.id.radioUserInfo:
            this.mTabHost.setCurrentTabByTag(TAB_TAG_INFO);
            HttpManager.getInstance().excutePost(
                    CommandFactory.updateCarStatus(LocationUploadService.getInstance().getCar()), new IHttpListener() {

                        @Override
                        public void onBack(boolean bSuccess, String strData, int nResponseCode) {
                            // TODO Auto-generated method stub
                            try {
                                JSONObject o = new JSONObject(strData);
                                if (UserInfoActivity.handler != null) {
                                    Message m = UserInfoActivity.handler.obtainMessage();
                                    m.what = CommandType.Update_Car_Status;
                                    m.obj = o;
                                    m.sendToTarget();
                                } else {
                                    Car c = LocationUploadService.getInstance().getCar();
                                    c.setLastPositionTime(o.getString("lastPositionTime"));
                                    c.setPosition(o.getString("position"));
                                    c.setCarryStatus(o.getString("carryStatus"));
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                Log.e(tag, e.getMessage(), e);
                            }

                        }
                    });
            break;
        case R.id.radioPosition:
            this.mTabHost.setCurrentTabByTag(TAB_TAG_POSITION);
            break;
        case R.id.radioMore:
            this.mTabHost.setCurrentTabByTag(TAB_TAG_MORE);
            break;
        }
    }

    private void bindService() {
        Intent intent = new Intent();
        intent.setClass(this, LocationUploadService.class);
        this.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

}
